package com.dbq.fast.business.login.business;

import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.bean.WeChatProfile;
import com.dbq.fast.business.login.bean.WeChatToken;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


public class WeChatLoginBiz {

    private IWXAPI iwxapi;
    private static WeChatLoginListener listener;
    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            SendAuth.Resp resp = (SendAuth.Resp) msg.obj;
            String code = resp.code;
            if(activity != null) {
                activity.getWindow().getDecorView().postDelayed(() -> {
                    if (activity == null) return;
                    if (activity.isFinishing()) return;
                    if (Build.VERSION.SDK_INT >= 17 && activity.isDestroyed()) return;
                    ProgressDialogUtil.showProgress(activity, "", App.getContext().getString(R.string.waiting));
                }, 300);
            }
            getWeChatToken(code);
        }
    };
    private static Activity activity;

    public WeChatLoginBiz(Activity context) {
        activity = context;
        iwxapi = WXAPIFactory.createWXAPI(context, WXEntryActivity.APP_ID);
        iwxapi.registerApp(WXEntryActivity.APP_ID);
    }

    public void login() {
        requestForCode();
    }

    //用于弹出授权登录页并获取返回码
    protected void requestForCode() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "dbq_fast";
        iwxapi.sendReq(req);
    }

    private static void getWeChatToken(String code) {
        LoginApi.getWCToken(code, new RemoteApiCallBack<WeChatToken>() {
            @Override
            public void onSuccess(WeChatToken weChatToken) {
                String token = weChatToken.getAccess_token();
                String openId = weChatToken.getOpenid();
                getUserInfo(token, openId);
            }

            @Override
            public void onFail(int status, String message) {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_WECHAT_LOGIN_GET_TOKEN);
                ProgressDialogUtil.hideProgress();
                Toast.makeText(App.getContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private static void getUserInfo(String token, String openId) {
        LoginApi.getWCProfile(token, openId, new RemoteApiCallBack<WeChatProfile>() {
            @Override
            public void onSuccess(WeChatProfile weChatProfile) {
                listener.weChatLoginSuccess(weChatProfile);
            }

            @Override
            public void onFail(int status, String message) {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_WECHAT_LOGIN_GET_INFO);
                ProgressDialogUtil.hideProgress();
                Toast.makeText(App.getContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public CustomProfile transProfile(WeChatProfile wcProfile) {
        CustomProfile profile = new CustomProfile();
        profile.setLoginChannel(1);
        profile.setPlatformId(wcProfile.getOpenid());
        profile.setUsername(wcProfile.getNickname());
        profile.setGender(wcProfile.getSex());
        if(wcProfile.getSex() == 1){
            profile.setSex("1");
        }else if(wcProfile.getSex() == 2){
            profile.setSex("2");
        }else {
            profile.setSex("3");
        }
        profile.setCountry(SystemUtil.getCountry(App.getContext()));
        profile.setProvince(wcProfile.getProvince());
        profile.setCity(wcProfile.getCity());
        profile.setHeadimgurl(wcProfile.getHeadimgurl());
        profile.setUuid(SystemUtil.getAndroidId(App.getContext()));
        profile.setIcon(wcProfile.getHeadimgurl());

        return profile;
    }

    public void destory() {
        activity = null;
    }

    public void setLoginListener(WeChatLoginListener listener) {
        this.listener = listener;
    }

    public interface WeChatLoginListener {
        void weChatLoginSuccess(WeChatProfile profile);
    }

}
